package com.own.component.common.util.encrypt.util;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * ShaUtil
 *
 * @author chenxueli
 * @date 2020/12/3 11:10
 */
@Slf4j
public class ShaUtil {

    /**
     * 加密
     *
     * @param content 加密内容
     * @return 加密后的内容
     */
    public String encrypt(String content, String type) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance(type);
            messageDigest.update(content.getBytes(StandardCharsets.UTF_8));
            return byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            log.error("加密失败", e);
            return content;
        }
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes 字节数组
     * @return 16进制字符串
     */
    private String byte2Hex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                builder.append("0");
            }
            builder.append(temp);
        }
        return builder.toString();
    }

}
